###################################################################################################
## Payson (2021) When Cities Lobby Replication Code
## Chapter Six Figures 6.1 - 6.3
## Created with R version 4.0.3 (2020-10-10) -- "Bunny-Wunnies Freak Out"
###################################################################################################

## Load packages
library(ggplot2); library(effects); library(stargazer); 
library(tidyverse); library(reshape); library(DataCombine)


## Set working directory
setwd()


## Functions for clean tex tables (need to define to compile tables)
pretty <- function(x) {
  paste(prettyNum(x, big.mark = ","))}

num.cities <- function(x) {
  length(which(getfe(x)=="fips"))}

N <- function(x) {
  x$N}

check <- "$\\checkmark$"

getmean <- function(x) {
  round(mean(x$response), 1)}



###################################################################################################
## Figure 6.1 Average State Transfer By City Income Tercile
###################################################################################################


dta <- read.csv("transfers_by_income.csv")


dta <- dta %>%
  group_by(state, year) %>%
  mutate(income.tercile = cut(median.income, breaks = quantile(median.income, probs = c(0, .33, .66, 1), na.rm = T),
                              labels = c("Bottom Tercile", "Middle Tercile", "Upper Tercile"), include.lowest = TRUE))


dta$year <- factor(dta$year)

m <- lm(state.rev.pp ~ income.tercile + log.pop + state + year, data = dta)


require(lattice)
trellis.par.set(grid.pars = list(fontfamily = "serif"))
plot(effect("income.tercile", m), colors = "black", xlab = "City Income Tercile",
     ylab = "Average State Transfer (Per Capita)", main ="")



###################################################################################################
## Figure 6.2 Lobbying and Share of State Transfers to High-Income Cities
###################################################################################################

dta <- read.csv("state_transfers.csv")

dta$year <- factor(dta$year)


m <- lm(prop.lobby ~ abbr + year, data = dta)
m1 <- lm(prop.high ~ abbr + year, data = dta[!is.na(dta$prop.lobby), ])

change.lobby <- resid(m)
change.prop.high <- resid(m1)

plot.dta <- data.frame(change.lobby = resid(m), change.prop.high = resid(m1),
                       state = m$model$abbr, year = m$model$year)

tmp <- subset(plot.dta, year == 2011)

(p <- ggplot(tmp, aes(x = change.lobby, y = change.prop.high)) +
    geom_point() +
    coord_cartesian(ylim=c(-.1, .12)) +
    geom_smooth(method = lm, formula = y ~ poly(x, 1), color = "black", se = F) + 
    annotate("text", x = tmp$change.lobby, 
             y = tmp$change.prop.high + .01, 
             label = tmp$state) +
    theme_bw(base_family = "serif") +
    theme(plot.background = element_blank(),
          panel.grid.major = element_blank(),
          panel.grid.minor = element_blank(),
          strip.background = element_rect(fill = "white")) +
    labs(y = expression(paste(Delta, " Share of Transfers to High Income Cities")),  
         x = expression(paste(Delta, " Proportion of Cities Lobbying"))))



###################################################################################################
## Figure 6.3 Figure 6.3 Predicted Effect of Lobbying on State Transfers to High Income Cities
###################################################################################################

dta <- read.csv("state_transfers.csv")

dta$year <- factor(dta$year)


m2 <- lm(prop.high ~ year + state + log.exp + house.dem.prop + gov.party + prop.lobby, data = dta[dta$num.city > 14,])

values <- list(prop.lobby = c(0, .1, .2, .3, .4, .5, .6, .7, .8))

plot.dta <- data.frame(prop.lobby = c(0, .1, .2, .3, .4, .5, .6, .7, .8),
                       lower = summary(effect("prop.lobby", m2, xlevels = values,
                                              confidence.level=.9))$lower,
                       upper = summary(effect("prop.lobby", m2, xlevels = values,
                                              confidence.level=.9))$upper,
                       effect = summary(effect("prop.lobby", m2, xlevels = values,
                                               confidence.level=.9))$effect)

(p <- ggplot(plot.dta, aes(prop.lobby, effect)) +
    geom_line() +
    geom_line(aes(x = prop.lobby, y = upper), linetype = "dashed") +
    geom_line(aes(x = prop.lobby, y = lower), linetype = "dashed") +
    theme_bw(base_family = "serif", base_size = 11) +
    theme(plot.background = element_blank(),
          panel.grid.major = element_blank(),
          panel.grid.minor = element_blank(),
          strip.background = element_rect(fill = "white")) +
    labs(x = "Proportion of Cities Lobbying", y = "Share of Transfers to High Income Cities"))

